<?
/**
 * VoiceOne Settings/MOH/edit
 *
 * Frontend to manage a music on hold class in voiceone.
 * @package voiceone
 * @subpackage  settings_moh
 */
include ("../../../admin/config/cfg.php");
global $cwlang; 
require_once("$absBasePath/lib/xajax/xajax.inc.php");
  
  //=================== XAJAX ==================
  function showProperty($mode){
    // Instantiate the xajaxResponse object
    $objResponse = new xajaxResponse();
    // Make response
    if($mode=="files"){
      $objResponse->addAssign("application_dt","style.display", "none");
      $objResponse->addAssign("application_dd","style.display", "none");
      }
    else{
      $objResponse->addAssign("application_dt","style.display", "block");
      $objResponse->addAssign("application_dd","style.display", "block");
    }
    //return the xajaxResponse object
    return $objResponse->getXML();  
  } 
  $xajax = new xajax();
  $xajax->registerFunction("showProperty");
  $xajax->processRequests();
  
  //=============== POST and GET ===============
  $alert=getAlert();
  // Populate setting value
  $default=$asterisk->getMohClass("default");
  $application=$default[0]["application"]; 
  //$application="/usr/bin/madplay -Q --attenuate=-12 --mono -R 8000 --output=RAW:-";
  if(count($_GET)>0){
    if(isset($_GET["name"])&&($_GET["name"]!="")){
      //Extract class information
      $ret=$asterisk->getMohClass($_GET["name"]); 
      $name=$ret[0]["name"];
      $mode=$ret[0]["mode"];
      $application=$ret[0]["application"];
      //Extract songs information
      $songsSelected=$asterisk->getMohSongs($name);
      foreach($songsSelected as $song){
        $listRight.="<option value=\"$song\">$song</option>";  
      }
      // display or not application text field
      if($mode=="files") $dis_app="display: none";
      else $dis_app="display: block";
    }
  }
  // Save class
  else if(count($_POST)>0){
    // Crate a new class
    if((!(isset($_POST["oldname"])))&&($_POST["class"]["name"]!="")){
      $def["name"]=$_POST["class"]["name"];
      $def["mode"]=$_POST["class"]["mode"];
      if($def["mode"]=="files") $def["application"]=$application;
      else $def["application"]=$_POST["class"]["application"];
      foreach($_POST["listRight"] as $song){
        $def["songs"][]=$song; 
      }
      $ret=$asterisk->createMohClass($def);
      if ($ret>0) {$alert="<div class=\"AlertGood\">".$cwlang["moh"]["alertCreateGood"]."</div>";
      } else $alert="<div class=\"AlertBad\">".$cwlang["moh"]["alertCreateBad"]."</div>";  
      goToMainPage($alert);
    }
    // Modify a class
    else if((isset($_POST["oldname"]))&&($_POST["oldname"]!="")){
      //Make new class definition
      $def["name"]=$_POST["oldname"];
      $def["mode"]=$_POST["class"]["mode"];
      $def["application"]=$_POST["class"]["application"];    
      foreach($_POST["listRight"] as $song){
        $def["songs"][]=$song; 
      }
      $ret=$asterisk->modifyMohClass($def);
      if($ret>0) {$alert="<div class=\"AlertGood\">".$cwlang["moh"]["alertModifyGood"]."</div>";
      } else $alert="<div class=\"AlertBad\">".$cwlang["moh"]["alertModifyBad"]."</div>";
      goToMainPage($alert);
    }
  }
  
  //================ PAGE LOGIC ================
  //Define page title
  if(isset($_GET["name"])&&($_GET["name"]!="")) $title=$cwlang["moh"]["modClass"]." \"".$name."\"";
  else $title=$cwlang["moh"]["newClass"];
  // Create modes list
  if($mode=="custom") $modeList.="<option value=\"custom\" selected=\"selected\">custom</option>\n";
  else $modeList.="<option value=\"custom\">custom</option>\n";
  if($mode=="mp3") $modeList.="<option value=\"mp3\" selected=\"selected\">mp3</option>\n";
  else $modeList.="<option value=\"mp3\">mp3</option>\n";
  if($mode=="mp3nb") $modeList.="<option value=\"mp3nb\" selected=\"selected\">mp3nb</option>\n";
  else $modeList.="<option value=\"mp3nb\">mp3nb</option>\n";
  if($mode=="quietmp3") $modeList.="<option value=\"quietmp3\" selected=\"selected\">quietmp3</option>\n";
  else $modeList.="<option value=\"quietmp3\">quietmp3</option>\n";
  if($mode=="quietmp3nb") $modeList.="<option value=\"quietmp3nb\" selected=\"selected\">quietmp3nb</option>\n";
  else $modeList.="<option value=\"quietmp3nb\">quietmp3nb</option>\n";
  if($mode=="files") $modeList.="<option value=\"files\" selected=\"selected\">files</option>\n";
  else $modeList.="<option value=\"files\">files</option>\n";
  // Create songs list
  $songsList=$asterisk->getMohSongs("");
  foreach($songsList as $song){
    $listLeft.="<option value=\"$song\" >$song</option>";  
  }
  //create a visual list of classes
  $ret=$asterisk->getMohClass("");
  $count=0;
  if (is_array($ret)){
    foreach($ret as $otherClass){
      $otherName=$otherClass["name"];
      $script.="\"$otherName\",";
    }
    if ($script!="") $script="<script> var alreadyDefinedClass=new Array(".substr($script, 0, -1).");</script>"; 
  }
  // create pannel var
  $add=$cwlang["moh"]["addButton"];
  $addAll=$cwlang["moh"]["addAllButton"];
  $remove=$cwlang["moh"]["removeButton"];
  $removeAll=$cwlang["moh"]["removeAllButton"];
 
  //================ MAIN CONTENTS ================
  ob_start();
  $xajax->printJavascript("../../../admin/lib/xajax/"); 
  ?>
  <?=$script?>
  <div class="SectionHeader">
  <?=$alert?>
    <h1><?=$title?></h1>
    <h3>
      <a href="../" class="admin"><?=$cwlang["moh"]["return"]?></a> 
    </h3>
  </div>
  <div id="basic_form">
    <form action="<?=$PHP_SELF?>" id="edit_form" method="post" onSubmit=" return selectAll(getElementById('listRight'));">
      <!-- Class setting -->
      <h2><?=$cwlang["moh"]["point1title"]?></h2>
      <p class="blockintro"><?=$cwlang["moh"]["point1text"]?></p>
      <table>
        <tr>
          <td>
            <div class="block" id="property">
              <dl>
                <? if(!(isset($_GET["name"]))) { ?>
                  <dt class="required"><label for="class[name]"><?=$cwlang["moh"]["calssName"]?>:</label></dt>
                  <dd><input type="text" size="25" maxlength="30" id="class[name]" name="class[name]" value=""></dd>
                <? } ?>                   
                <dt class="required"><label for="class[mode]"><?=$cwlang["moh"]["classMode"]?>:</label></dt>
                <dd><select id="class[mode]" name="class[mode]" onChange="xajax_showProperty(this.value);"><?=$modeList?></select></dd>
                <dt class="required" id="application_dt" style="<?=$dis_app?>"><label for="client[language]"><?=$cwlang["moh"]["classApplication"]?>:</label></dt>
                <dd id="application_dd" style="<?=$dis_app?>"><input type="text" size="100" maxlength="100" id="class[application]" name="class[application]" value="<?=$application?>"/></dd> 
              </dl>  
            </div>
          </td>
        </tr>
      </table>  
      <!-- Songs selection -->
      <div id="songList">
      	<h2><?=$cwlang["moh"]["point2title"]?></h2>
        <p class="blockintro"><?=$cwlang["moh"]["point2text"]?></p>
        <div class="block">
          <table>
            <tr>
              <td class="required">
                <div ><?=$cwlang["moh"]["availableSongs"]?>:</div>
                <select multiple size="10"  name="listLeft[]" id="listLeft"><?=$listLeft?></select>
              </td>
              <td>   
                <div><input type="button" onclick="addDualList(document.getElementById('listLeft'), document.getElementById('listRight'), false)" name="Add     >>"  value="<?=$add?>>>" style="width:100px"></div>
                <div><input type="button" onclick="removeDualList(document.getElementById('listRight'), false )" name="Add     <<"  value="<<<?=$remove?>" style="width:100px"></div>
                <div><input type="button" onclick="addDualList(document.getElementById('listLeft'), document.getElementById('listRight'), true)" name="Add All >>"  value="<?=$addAll?>>>" style="width:100px"></div>
                <div><input type="button" onclick="removeDualList(document.getElementById('listRight'), true)" name="Add All <<"  value="<<<?=$removeAll?>" style="width:100px"></div>
              </td>
              <td class="required"><div ><?=$cwlang["moh"]["selectedSongs"]?>:</div>
                <div style="float: left">
                  <input type="image"  src="<?=$relBasePath?>public/img/icon_up.gif"  onclick="moveOptions ( document.getElementById('listRight'), -1); return false" name="Up"  value="Down" style="display: block">
                  <input type="image"  src="<?=$relBasePath?>public/img/icon_down.gif"  onclick="moveOptions ( document.getElementById('listRight'), 1); return false;" name="Down"  value="Down" style="display: block">
                </div>
                  <select multiple size="10" name="listRight[]" id="listRight"><?=$listRight?></select>
              </td>
            </tr>
          </table>
        </div>
      </div>
      <!-- Input Buttons -->
      <div class="action">
        <?if ($_GET["name"]!="") {?> <input type="hidden" id="oldname" name="oldname" value="<?=$_GET[name]?>" /><?}?>
        <input type="image" src="<?=$relBasePath?>/public/img/<?=$cwLanguage?>/b-cancel.gif" alt="Cancel" onclick="location.href='../'; return false;"/>
        <input type="image" src="<?=$relBasePath?>/public/img/<?=$cwLanguage?>/b-save.gif" alt="Save" onclick="return checkData();"/>
      </div>
   </form>
  </div>     
  
  <script>
    function checkData(){
      nameObj=document.getElementById("class[name]");
      if(nameObj!=null) {
        var newClassName = nameObj.value;
        if(newClassName==""){ 
          alert('Please insert class name');
          return false; // empty name field
        } 
        else{
          var currentClass=null;
          for (var i=0; i<alreadyDefinedClass.length; i++) {
            currentClassName=alreadyDefinedClass[i];
            if(newClassName==currentClassName) {
              alert('\"' + newClassName + '\" already exist. Please change class name'); 
              return false; // name already exist
            }
          }
        }
      }
      else var newClassName = document.getElementById("oldname").value;
      var count = 0;
      songsList = document.getElementById("listRight");
      for(var i=0; i<songsList.childNodes.length; i++) {
        currObj=songsList.childNodes[i];
        if(currObj.tagName=="OPTION") count++; 
      }      
      if(count == 0) {
        alert('There are no songs assigned to \"' + newClassName + '\" \n   Please assign songs to the class');
        return false; // empty songs list
      } 
      // check if name contains strange characters   
      var ch=null;
      for(var i=0; i<newClassName.length; i++) {
        ch = newClassName.charCodeAt(i);
        if (!(((ch>96)&&(ch<123))||((ch>64)&&(ch<91))||((ch>47)&&(ch<58))||(ch==95)||(ch==32))) {
          alert('Character "' + newClassName.charAt(i) + '" is not permitted. Please change class name');
          return false;
        }
      } 
      return true;
    }
  </script>
    
  <? 
  $contents=ob_get_contents();
  ob_end_clean();
  //================ SIDEBAR ================
  ob_start(); 
  ?>
        <div class="Sidebar">
          <h1><?=$cwlang["moh"]["editSidebarTitle"]?></h1>
          <?=$cwlang["moh"]["editSidebarDesc"]?>
        </div>
  <?  
  $sidebar=ob_get_contents();
  ob_end_clean();
  //================ SETTINGS ================
  $smarty->assign("section", "moh");
  $smarty->assign("subsection", "");
  $smarty->assign("templateType", "TwoColLeft");  //OneCol, TwoColLeft, TwoColRight
  $smarty->assign("contents", $contents);
  $smarty->assign("sidebar", $sidebar);
  $smarty->display('settings.tpl');
?>
